package com.aopeng.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 异常拦截器类
 */
@ControllerAdvice
public class ControllerExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /*自定义异常*/
    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler(HttpServletRequest request, Exception e) throws Exception {
        //记录日志
        logger.error("Request URL : {}, Exception : {}", request.getRequestURL(), e);

        //如果异常定义了就不拦截,让它抛出
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;    //抛出异常
        }

        ModelAndView mv = new ModelAndView();
        //前端页面的url存放到对象
        mv.addObject("url", request.getRequestURL());
        //存放异常信息
        mv.addObject("exception", e);
        //设置返回到指定页面
        mv.setViewName("error/error");
        return mv;
    }
}
